NestJS之16 您所在的位置:网站首页 nestjs 中文文档 NestJS之16

NestJS之16

2023-04-23 16:35| 来源: 网络整理| 查看: 265

1. 安装配置

安装 npm install @nestjs/swagger swagger-ui-express

main.ts

import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; async function bootstrap() { const app = await NestFactory.create(AppModule); const options = new DocumentBuilder() .setTitle('接口文档') .setDescription('描述信息') .setVersion('1.0.0') .build(); const document = SwaggerModule.createDocument(app, options); SwaggerModule.setup('/api-docs', app, document); await app.listen(3000); } 复制代码

image.png

2. 添加分组

guard.controller.ts

import { ApiTags } from '@nestjs/swagger'; @Controller('guard') @ApiTags('守卫接口') // 分组 @UseGuards(RoleGuard) 复制代码

image.png

3. 添加单个接口描述信息 import { ApiOperation } from '@nestjs/swagger'; @Get() @Role('admin') // 自定义名称 数据 @ApiOperation({ summary: 'get接口', description: '角色' }) findAll(@MyParam() param: string) { console.log('打印***param', param); return this.guardService.findAll(); } 复制代码

image.png

4. 接口参数描述 @Get(':id') @ApiParam({ name: 'id', description: '获取单个数据', required: true, }) findOne(@Param('id') id: string) { return this.guardService.findOne(+id); } 复制代码

image.png

5. query 参数描述 @Get() @Role('admin') // 自定义名称 数据 @ApiQuery({ name: 'page', description: '分页信息', required: true, type: String, }) findAll(@MyParam() param: string) { console.log('打印***param', param); return this.guardService.findAll(); } 复制代码

image.png

6. 自定义返回信息 @Get() @Role('admin') // 自定义名称 数据 @ApiResponse({ status: 403, description: '88' }) findAll(@MyParam() param: string) { console.log('打印***param', param); return this.guardService.findAll(); } 复制代码

image.png

7. post参数装饰

结合dto进行使用

create-guard.dto.ts

import { ApiProperty } from '@nestjs/swagger'; export class CreateGuardDto { @ApiProperty({ example: 'jack', type: String }) name: string; @ApiProperty() age: number; } =====================post中不用写=================== @Post() create(@Body() createGuardDto: CreateGuardDto) { return this.guardService.create(createGuardDto); } 复制代码

image.png

8. 添加token信息

main.ts

const options = new DocumentBuilder() .addBearerAuth() // 此处添加 .setTitle('接口文档') .setDescription('描述信息') .setVersion('1.0.0') .build(); 复制代码

guard.controller.ts

@Controller('guard') @ApiTags('守卫接口') // 分组 @ApiBearerAuth() @UseGuards(RoleGuard) export class GuardController {} 复制代码

image.png

image.png

image.png



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有